export interface IRequestOptions {
    method: 'GET' | 'POST' | 'PUT' | 'DELETE';
    headers: { [key: string]: string };
    url: string;
    param?: BodyInit;
}

// 定义拦截器的接口
interface Interceptor<T> {
    onFulfilled?: (value: T) => T | Promise<T>;
    onRejected?: (error: any) => any;
}

// 定义拦截器管理类
export class InterceptorManager<T> {
    private interceptor: Interceptor<T>;

    // 添加拦截器的方法
    use(interceptor: Interceptor<T>) {
        this.interceptor = interceptor;
    }

    // 获取拦截器的方法
    getInterceptor() {
        return this.interceptor;
    }
}

// 使用单个拦截器的 request 函数
export async function httpRequest<T>(options: IRequestOptions, requestInterceptorManager: InterceptorManager<IRequestOptions>, responseInterceptorManager: InterceptorManager<Response>) {
    try {
        // 如果有请求拦截器，则执行
        const requestInterceptor = requestInterceptorManager.getInterceptor();
        if (requestInterceptor?.onFulfilled) {
            options = await requestInterceptor.onFulfilled(options);
        }
        let response = await fetch(options.url,
            {
                method: options.method,
                headers: options.headers,
                body: JSON.stringify(options.param)
            });
        // 如果有响应拦截器，则执行
        const responseInterceptor = responseInterceptorManager.getInterceptor();
        if (responseInterceptor?.onFulfilled) {
            response = await responseInterceptor.onFulfilled(response);
        }
        return response;
    } catch (error) {
        const responseInterceptor = responseInterceptorManager.getInterceptor();
        if (responseInterceptor?.onRejected) {
            await responseInterceptor.onRejected(error);
        }
    }
}
